package ltd.smallwang;

import java.util.HashMap;
import java.util.Map;

/**
 * @author smallwang
 * @email justdoalitter@gmail.com
 * @create date 2025-01-01 21:55:32
 * @modify date 2025-01-01 21:55:32
 * @desc [description]
 */
public class Leetcode0383 {

  public boolean canConstruct(String ransomNote, String magazine) {
    if (ransomNote.length() > magazine.length()) {
      return false;
    }
    return method02(ransomNote, magazine);
  }

  private boolean method02(String ransomNote, String magazine) {
    int[] charArr = new int[26];
    for (char item : magazine.toCharArray()) {
      charArr[item - 'a']++;
    }
    for (char item : ransomNote.toCharArray()) {
      int count = charArr[item - 'a'];
      if (count <= 0) {
        return false;
      }
      charArr[item - 'a']--;
    }
    return true;
  }

  @SuppressWarnings("unused")
  private boolean method01(String ransomNote, String magazine) {
    Map<Character, Integer> magazineMap = HashMap.newHashMap(10);
    for (int i = 0; i < magazine.length(); i++) {
      Character item = magazine.charAt(i);
      if (magazineMap.containsKey(item)) {
        magazineMap.put(item, magazineMap.get(item) + 1);
      } else {
        magazineMap.put(item, 1);
      }
    }
    for (int i = 0; i < ransomNote.length(); i++) {
      Character item = ransomNote.charAt(i);
      if (magazineMap.containsKey(item)) {
        int value = magazineMap.get(item);
        if (value <= 0) {
          return false;
        }
        magazineMap.put(item, value - 1);
      } else {
        return false;
      }
    }
    return true;
  }
}
